<?php
/**
 * 后台panx管理员登录中间件
 *
 * Author: Zeon
 * Date: 2017/11/20
 * Created by Panxsoft.
 */
namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use App\Exceptions\ApiErrCode;
use App\Models\Admin\PanxAdmin;
use App\Models\Panx\Panx;
use App\Services\Utils\ApiChecker;
use App\Services\Locale\Language;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTGuard;

class AdminAuth {

    use ApiChecker;

    /** @var  Panx $panx */
    public static $panx;

    /** @var  PanxAdmin $panx_admin */
    public static $panx_admin;

    /**
     *
     * @example composer require tymon/jwt-auth@1.0.0-beta.3
     * @link http://jwt-auth.readthedocs.io/en/docs/quick-start/
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function handle(Request $request, Closure $next)
    {
        $this->checkToken($request);

        /** @var JWTGuard $jwt */
        $jwt = Auth::guard('panx');

        /** @var PanxAdmin|null $admin */
        $admin = $jwt->user();
        if (! $admin) {
            throw new ApiException(ApiErrCode::JWT_TOKEN_INVALID, trans('middleware.token_invalid'));
        }
        $this->checkAdminStatus($admin);

        // 设置语言信息
        Language::setAppLocale($admin->language);

        self::$panx_admin = $admin;
        self::$panx = $admin->panx;

        return $next($request);
    }

    /**
     * @param Request $request
     *
     * @throws ApiException
     */
    private function checkToken(Request $request): void
    {
        if (config('app.debug_admin')) return;
        
        $this->checkJwtTokenExist($request, trans('checker.check_jwt_token_exist'));
    }

    /**
     * @param $admin
     */
    private function checkAdminStatus(PanxAdmin $admin): void
    {
        $this->checkUnless(
            $admin->is_deleted,
            trans('middleware.account_disabled')
        );
    }
}